<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com> <http://www.jxlnxx.com>
// +----------------------------------------------------------------------

namespace Home\Controller;

/**
 * 前台拍真宝控制器
 * 主要获取拍真宝聚合数据
 */
class PzbController extends HomeController {
    
    /**
     * 拍真宝首页
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function index(){
        
        $M_product=M('product');
        $M_product_image=M('product_image');
        
        $page=I('page',1);
        $pagesize=8;        
        $page <=0 && $page=1;        
        $offset=($page-1)*$pagesize;        
        $map=array('type'=>'paipin','is_show'=>1,'status=1');        

        $M_product_category=M('product_category');
        $cid=I('request.cid');
        $fid=I('request.fid');
        
        if($cid){
            $map['category_id']=$cid;
        }
        
        else if($fid){
            $cids=$M_product_category->where(array('pid'=>$fid))->field('id')->select();
            $cids=arr2tostr($cids);
            $map['category_id']=array('in',$cids);
        }
        
        $extend=I('extend');
        if($extend){
            switch($extend){
            case  'begin':
                $map['start_time']=array('BETWEEN',array(NOW_TIME,NOW_TIME+3600));
                break;
            case  'end':
                $map['end_time']=array('BETWEEN',array(NOW_TIME,NOW_TIME+3600));
                break;
            case  'zero':
                $map['price_start']=0;
                break;
            }
        }
        
        $total=$M_product->where($map)->count();
        $product_list=$M_product->where($map)->order('auction_count DESC')->select();
            
        foreach ($product_list as &$item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))->order('id ASC')->find();
           
            $item['image'] = get_cover($image_info['cover_id'],'path');
           if($item['bo_over']==1){
               //页面判断时间时显示为已结束
               $item['end_time']=NOW_TIME-1;
           }
        }
        
        //精选
        $delicacymap=array();
        
        $delicacymap['is_delicacy']=1;
        $product_delicacy_list=$M_product->where($delicacymap)->limit(0,6)->order('id DESC')->select();        

        foreach ($product_delicacy_list as &$item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))
            ->order('id ASC')->find();        
            $item['image'] = get_cover($image_info['cover_id'],'path');
        }
        $this->assign('delicacy_list',$product_delicacy_list);
        
        //广告
        $ad_positon=M('ad_position')->where(array('identifier'=>'ad_paipintop'))->find();
      
        $adlist=M('ad')->where(array('position_id'=>$ad_positon['id']))
        ->order('sort DESC')->field('cover_id,title,link,product_id')->select();
        foreach($adlist as &$item){
            $item['image']=get_cover($item['cover_id'],'path');
        }
      
       $this->assign('adlist',$adlist);
        
        $this->assign('p_list',$product_list);
     
        $this->display();
    }
    
    
    
    //竞拍详细
    public function  auctionDetail(){
       
        $id=I('id');       
        
        $M_product=M('product');
        $M_product_image=M('product_image');
        $M_auaction_per=M('auaction_permission');
        $M_auction_log=M('auction_log');
        $info=$M_product->find($id);
        //记录我足迹
        recordMybrowse($id);
        switch ($info['type']){
            case 'putong':
            $this->redirect('product/detail',array('id'=>$id));
            break;
        }
        empty($info) && $this->error('商品不存在',U('Index'));
       
        //时间
        $info['end_time']<NOW_TIME ? $info['is_stop']=1 : $info['is_stop']=0;
        //拍卖完结
       if($info['bo_over'] ==1){  
           //时间也设为结束
           $info['end_time']=NOW_TIME-1; 
           $info['is_stop']=1;
       }
        
        $M_product->where(array('id'=>$id))->setInc('view',1);
        
        $images =$M_product_image ->where(array('product_id'=>$info['id']))
        ->order('id ASC')->select();
    
        $latpath=array();
        foreach ($images as &$item){
            $item['path']= get_cover($item['cover_id'],'path');
        }
     
        $info['images']=$images;
        $info['signupcount']=$M_auaction_per->where(array('uid'=>UID,'product_id'=>$id))->count();
        $info['bidcount']=$M_auction_log->order('id DESC')->where(array('product_id'=>$id))->getfield('auction_no')|0;    
        
        $M_auaction_per=M('auaction_permission');
        if($M_auaction_per->where(array('uid'=>UID,'product_id'=>$id))->find()){
            $info['is_auaction_permission']=1;
        }else{
            $info['is_auaction_permission']=0;
        }
        
        $M_auction_log=M('auction_log');
        
        //最新出价
        $bid_log=$M_auction_log->where(array('product_id'=>$id))->order('id DESC')->find();
       
        $info['top_price']=$bid_log['price'];  
        
        if($bid_log['uid']==UID ){
            $this->assign('is_confirm',$bid_log['is_comfirm']);
        }
        //精选
        $delicacymap=array();
        
        $delicacymap['is_delicacy']=1;
        $product_delicacy_list=$M_product->where($delicacymap)->limit(0,6)->order('id DESC')->select();        

        foreach ($product_delicacy_list as &$item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))
            ->order('id ASC')->find();        
            $item['image'] = get_cover($image_info['cover_id'],'path');
        }
        $this->assign('delicacy_list',$product_delicacy_list);
    
        foreach (delicacymap as &$item) {
            $item['price']=(int)$item['price'];
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))
            ->order('id ASC')->find();
            $item['image'] = get_cover($image_info['cover_id'],'path');
        }
        $this->assign('salestop',delicacymap);    
    
        $this->assign('info',$info);
        $this->display();
    }
    
    function currentInfo(){        
        $product_id=I('id');        
        $M_product=M('product');
        $M_auction_log=M('auction_log');
        $M_auaction_per=M('auaction_permission');
        
        $maymap=array('product_id'=>$product_id,'uid'=>UID);        
        $lmy_last_bid=$M_auction_log->where($maymap)->order('id DESC')->find();
        //最新出价
        $bid_log=$M_auction_log->where(array('product_id'=>$product_id))->order('id DESC')->find();
        $result=array();
        $result=$bid_log;
        //报名人数
        $result['signupcount']=$M_auaction_per->where(array('uid'=>UID,'product_id'=>$product_id))->count();
        //我的出价
        $result['my_bid_price']=$lmy_last_bid['price'];
        //围观次数
        $result['view']=$M_product->where(array('id'=>$product_id))->getfield('view');
        if((int)$lmy_last_bid['id'] == (int)$bid_log['id']){
            $result['my_first']=1;
        }else{
            $result['my_first']=0;
        }
        $bid_log   ? $this->ajaxReturn(array('status'=>1,'result'=>$result)): 
        $this->ajaxReturn(array('status'=>-2));        
        
    }
    
    /**
     * 获取商品竞价记录列表
     *
     * @param integer page 页码
     * @return Ambigous <multitype:, mixed>
     */
    public function getBondlogs(){
        $product_id = I('request.product_id', 0);
        $p = I('request.p', 1);
        $p <=0 && $p=1;
        $pagesize = 10;
        $offset = ($p - 1) * $pagesize;
    
        $M_auction_log=M('auction_log');
        $map=array('product_id'=>$product_id);
        $total=$M_auction_log->where($map)->count();
        $list=$M_auction_log->where($map)->field('id,create_time,uid,price')
        ->limit($offset,$pagesize)
        ->order('id DESC')->select();
    
        $i=1;
        foreach($list as &$item){
            if($i==1){ $item['status_text']='最高';}
            else{
                $item['status_text']='出局';
            }
            $i++;
            $nickname=get_nickname($item['uid']);
            $item['nickname']=substr_cut($nickname);
    
            $item['format_time']=time_format($item['create_time'],'Y-m-d H:m:s');
        }
    
        $__PAGE__ = new \Think\Page($total, $pagesize);
        $__PAGE__->lastSuffix = false;
        $__PAGE__->rollPage = 6;
        $__PAGE__->setConfig('prev', '<');
        $__PAGE__->setConfig('next', '>');
        $__PAGE__->setConfig('first', '<<');
        $__PAGE__->setConfig('last', '<span>...</span>');
        $__PAGE__->setConfig('header', '<span>共%TOTAL_PAGE%页</span>');
        $__PAGE__->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %END% %DOWN_PAGE% %HEADER%');
        $__PAGE__->setConfig('ajax-url', true);
    
        $this->ajaxReturn(array('results'=>$list, 'pages'=>$__PAGE__->show()));
    }
    /**
     * 竞拍报名
     * @param int product_id
     */
    public function paipinSignup(){
       !is_login() && $this->error('请先登录'); 
        
        $product_id=I('request.product_id');
         
        $M_product=M('Product');
        $M_member=M('member');
         
        $product_info=$M_product->field('cash_deposit,end_time,title,type')->find($product_id);
        empty($product_info) && $this->error('商品不存在');
    
        $product_info['type'] != 'paipin' && $this->error('当前商品不是竞拍商品');
        $member_info=$M_member->where(array('uid'=>UID))->find();
    
        (int)$product_info['end_time'] < (int)NOW_TIME && $this->error('本次竞拍已结束');
        (double)$product_info['cash_deposit'] > (double)$member_info['amount'] && $this->error('余额不足');
    
        $M_auaction_per=M('auaction_permission');
        $M_auaction_per->where(array('uid'=>UID,'product_id'=>$product_id))->find() &&
        $this->success('您已经已经提交保证金');
    
        $data=array();
        $data['product_id']=$product_id;
        $data['uid']=UID;
        $data['cash_deposit']=$product_info['cash_deposit'];
        $data['create_time']=NOW_TIME;
         
        $result=$M_auaction_per->add($data) ;
        empty($result)  && response(-9);
        $bill_data=array();
        $bill_data['uid']=UID;
        $bill_data['create_time']=NOW_TIME;
        $bill_data['title']='竟拍报名保证金 冻结金额'.$data['cash_deposit'];
        $bill_data['desc']=$product_info['title'];
        $bill_data['sign']='-';
        $bill_data['type']=3;
        $bill_data['money']=$data['cash_deposit'];
        $bill_data['status']=1;
    
        M('bill')->add($bill_data);
         
        $result= $M_member->where(array('uid'=>UID))->setDec('amount',$data['cash_deposit']);
        empty($result) && $this->error('系统错误');
        $result=$M_member->where(array('uid'=>UID))->setInc('freeze_amount',$data['cash_deposit']);
        
        empty($result) && $this->error('系统错误');
    
        $this->success('报名成功');
    }
    
    
    /**
     * 出价
     */
    function bid(){
        !is_login() && $this->error('请先登录');
        
        $product_id=I('product_id');
        $money=I('money');
        if(empty($product_id)){
            $this->error('竞拍商品不存在');
        }
        if(empty($money)){
           $this->error('出价不能为空');
        }
        $M_bill= M('bill');
        $M_product=M('Product');
        $M_member=M('member');
        $M_auaction_per=M('auaction_permission');
        $M_auction_log=M('auction_log');
        
        !is_numeric($money) || empty($money) && $this->error('出价错误');
        
        $product_info=$product_info=$M_product
        ->field('cash_deposit,end_time,title,price_start')->find($product_id);
        empty($product_info) && $this->error('竞拍商品不存在');
        
        $product_info['bo_over']==1 && $this->error('本次竞拍已完结');
        (int)$product_info['end_time'] < (int)NOW_TIME && $this->error('本次竞拍已结束');
        
        (int)$product_info['price_start'] > $money && $this->error('出价不能低于起拍价');
        
        $auaction_authority=$M_auaction_per->where(array('uid'=>UID,'product_id'=>$product_id));
        empty($auaction_authority) && $this->error('未报名');
        
        //最新出价
        $au_log_after=$M_auction_log->where(array('product_id'=>$product_id))
        ->order('id DESC')->find();
        
        //上一次出价
        $old_auction=$M_auction_log->where(array('product_id'=>$product_id,'uid'=>UID))
        ->order('id DESC')->find();
        if($old_auction){
        //判断是否重复竞拍
        $au_log_after['id'] == $old_auction['id'] && $this->error('请等待别人出价');
        }
        $maxprice=(int)$product_info['maxprice'];
        //最高出价
        (int)$au_log_after['price'] >= (int)$money  && $this->error('出价不能低于当前最高出价');
        
        $member_map=array('uid'=>UID);
        
        if($old_auction){
            $refz_amount=$M_member->where($member_map)->setInc('amount',$old_auction['price']);
            $refz_amount<=0 && $this->error('解冻资金出错');
            $reefed=$M_member->where($member_map)->setDec('freeze_amount',$old_auction['price']);
            if($reefed<=0){
                $refz_amount=$M_member->where($member_map)->setDec('amount',$old_auction['price']);
                $this->error('解冻资金出错');
            }
            if($refz_amount  && $reefed )
            {
                $bill_data=array();
                $bill_data['uid']=UID;
                $bill_data['create_time']=NOW_TIME;
                $bill_data['sign']='+';
                $bill_data['money']=$money;
                $bill_data['type']=4;
                $bill_data['title']='竟拍解冻 金额：'.$money;
                $bill_data['desc']=$product_info['title'].' 竟拍解冻 金额：'.$money;
                $bill_data['status']=1;
                $M_bill->add($bill_data);  
                }
            else{
                $this->error('系统异常');
            }
        }
        
        $re_fz=$M_member->where($member_map)->setInc('freeze_amount',$money);
        $re_fz <=0 && $this->error('冻结资金1出错');
        $re_fz_dm=$M_member->where($member_map)->setDec('amount',$money);        
        if($re_fz_dm <=0){
            $re_fz=$M_member->where($member_map)->setDec('freeze_amount',$money);
            $this->error('更新用户余额出错');
        }
        if($re_fz && $re_fz_dm){
            $data=array();
            $data['uid']=UID;
            $data['product_id']=$product_id;
            $data['create_time']=NOW_TIME;
            $data['price']=$money;            
            $data['auction_no']=(int)$au_log_after['auction_no'] +1;
        
            $result=$M_auction_log->add($data);
            empty($result) && $this->error('系统出现错误');
        
            //账单信息
            $bill_data=array();
            $bill_data['uid']=UID;
            $bill_data['create_time']=NOW_TIME;
            $bill_data['title']='竟拍出价'.$money;
            $bill_data['desc']=$product_info['title'].' 竞拍冻结资金  金额：'.$money;
            $bill_data['sign']='-';
            $bill_data['money']=$money;
            $bill_data['type']=3;
            $bill_data['status']=1;
        
            $M_bill->add($bill_data);
        
            $M_product->where(array('id'=>$product_id))->setInc('auction_count',1);
            
            if($maxprice<=$money){
                $M_product->where(array('id'=>$product_id))->save(array('bo_over'=>1,'update_time'=>NOW_TIME));
                addMessage(2,'竞拍通知','恭喜您收得宝贝'.$product_info['title'].',请尽快去确认',UID);
                $this->ajaxReturn(array('status'=>100,'info'=>"恭喜您拍得宝贝!!"));
            }          
        }
        $this->error("出价失败");
    }
    
    /**
     * 保存 
     */
    public function save(){
  
        !is_login() && $this->error('请您先登录');
        $M_product_image = M('product_image');
        $M_product=M('product');
        $M_auction_log=M('auction_log');
        
        $product_id=I('id');
        
        empty($product_id) && $this->redirect('Pzb/index');
        
        $auction_log_info=$M_auction_log->where(array('uid'=>UID,'product_id'=>$product_id))->order('id DESC')->find();
        if(empty($auction_log_info)){
            $this->error('非法操作,您不是得主！！',U('Pzb/auctionDetail',array('id'=>$product_id)));
        }
        if($auction_log_info['is_comfirm']==1){           
            $this->error('竞拍已经完结,重复下单无效',U('Pzb/auctionDetail',array('id'=>$product_id)));           
        }        
        
        
        $M_product_image=M('product_image');
        $M_product=M("product");
        $M_cart=M('cart');
        $product_info=$M_product->field('title,price,category_id')->find($product_id);        
    
        $data=array();
        $data['productd_title']=$product_info['title'];
        $data['quantity']=1;
        $data['price']=(double)$auction_log_info['price'];
        $data['product_id']=$product_id;
        $data['unit_price']=$product_info['price'];
        $data['uid']=UID;
        $data['create_time']=NOW_TIME;
        $data['update_time']=NOW_TIME;
        $data['status']=1;
        $data['option_ids']=0;
        $data['product_attr']='';
        $identify_price = (double)get_table_field($product_info['category_id'],'product_category_id','price','identify') | 0;
       
        $images = $M_product_image->where(array('product_id'=>$product_id))->find();
        $data['image_path']= get_cover($images['cover_id'], 'path');
        
        $this->assign('identify_price',$identify_price);
        $this->assign('totalprice',$data['price']);
        $this->assign('auction_log_id',$auction_log_info['id']);
        
        $this->assign('product_list',array($data));
         
        //地址
        $M_member_receive=M('member_receive');
        $receive_list=$M_member_receive->where(array('uid'=>UID))->select();
       
        foreach($receive_list as &$item){
            $item['address_full']=
            get_table_field($item['province_id'],'province_id','province','hat_province')
            .get_table_field($item['city_id'],'city_id','city','hat_city')
            .get_table_field($item['area_id'],'area_id','area','hat_area');
        }
        $this->assign('receive_list',$receive_list);
       
        $this->display();      
         
    }
    
    /**
     * 完成下单
     */
    public function submitJp(){
        if(IS_POST){
        !is_login() && $this->error('请您先登录');
            
        $receive_id=I('post.receive_id');
        $price=(double)I('price');
        $productid=I('post.productid');
        $auction_log_id=I('auction_log_id');
        
        $M_auction_log=M('auction_log');
        $auction_log_info=$M_auction_log->where(array('id'=>$auction_log_id))->order('id DESC')->find();
        
        if($auction_log_info['uid'] !== UID){
            $this->error('非法操作',U('Pzb/index'));
        }   
        
        if($auction_log_info['is_confirm'] == 1){
            $this->error('您已经确定确定了此次订单 请勿重复下单',U('Pzb/index'));
        }
        $M_auction_log->where(array('id'=>$auction_log_id))->save(array('is_confirm'=>1));
        
        
        $M_order=M('order');
        $M_product=M('product');
        $M_order_product=M("order_product");
        $M_receive=M('member_receive');
        $M_member=M('member');
        $M_bill=M('bill');
        //商品信息
        $product_info=$M_product->field('uid,shop_id,title,price,category_id')->find($productid);
        $receive_info=$M_receive->find($receive_id);
        $order_data=array();
        $order_data['address']=$receive_info['address'];
        $order_data['consignee']=$receive_info['realname'];
        $order_data['mobile']=$receive_info['mobile'];
        $order_data['province_id']=$receive_info['province_id'];
        $order_data['city_id']=$receive_info['city_id'];
        $order_data['area_id']=$receive_info['area_id'];
        $order_data['create_time']=NOW_TIME;
        $order_data['update_time']=NOW_TIME;
        $order_data['status']=0; /*未付款*/
        $order_data['uid']=UID;       
        $order_data['price']=$price;
        //生成订单号
        $order_data['order_no']=build_no();        
        
        $quantity=I('post.quantity');
        $product_data=array();
    
        $product_data['quantity']=$quantity;
        $product_data['price']=$price;
        $product_data['unit_price']=(double)$price;
        $product_data['product_id']=$productid;
        $product_data['product_title']=$product_info['title'];
        $product_data['shop_id']=$product_info['shop_id'];
        $product_data['identify_price']=  get_table_field($product_info['category_id'],'product_category_id','price','identify') | 0;
        $product_data['create_time']=NOW_TIME;
        $product_data['update_time']=NOW_TIME;
        $product_data['option_ids']=0;
        $product_data['product_attr']='默认';
     
        
        //保存订单 
        $order_id=$M_order->add($order_data);
        if(empty($order_id)){
            $this->error('系统出现故障，请联系管理员');
        }
        $now_order_id[]=$order_id;
        $now_order_no[]=$order_data['order_no'];
        addMessage(2,'订单通知','您竞拍获得的宝贝'.$product_info['title'].'订单'.$order_data['order_no'].'已经确认,请及时付款',UID);
        $product_data['order_id']=$order_id;
         if($order_id){
             //保存订单商品
           $or_p_add= $M_order_product->add($product_data);
           empty($or_p_add) && $this->error('系统故障 ');
         }
         //冻结资金解冻---开始
         $member_map=array('uid'=>UID);
         
         $refz_amount=$M_member->where($member_map)->setInc('amount',$price);
         $refz_amount<=0 && $this->error('解冻资金出错');
         $reefed=$M_member->where($member_map)->setDec('freeze_amount',$price);
         if($reefed<=0){
             $M_member->where($member_map)->setDec('amount',$price);
             $this->error('解冻资金出错');
         }
         if($refz_amount  && $reefed )
            { 
             $bill_data=array();
             $bill_data['uid']=UID;
             $bill_data['create_time']=NOW_TIME;
             $bill_data['sign']='+';
             $bill_data['money']=$price;
             $bill_data['type']=4;
             $bill_data['title']='竟拍解冻 金额：'.$price;
             $bill_data['desc']=$product_info['title'].' 竟拍解冻 金额：'.$price;
             $bill_data['status']=1;
             $M_bill->add($bill_data);
         }
         else{
             $this->error('系统异常');
         }
        
         //冻结资金解冻---结束
        
        empty($now_order_id) && $this->error('下单失败');
        $param=array();
        $param['order_id']=implode(',', $now_order_id);
        $param['order_no']=implode(',', $now_order_no);
        $this->success('下单成功,即将跳转到支付页面',U('order/pay',$param));
        
        } 
    }
}
?>